package com.dlnu.shoping.shopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dlnu.shoping.shopping.common.Result;
import com.dlnu.shoping.shopping.entity.User;
import com.dlnu.shoping.shopping.mapper.UserDao;
import com.dlnu.shoping.shopping.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Override
    public Result search(String userId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("use_id",userId);
        return new Result(userDao.selectOne(wrapper));
    }

    @Override
    public Result register(String name, String nickname, String tel, String password) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("tel_num",tel);
        User user = userDao.selectOne(wrapper);
        if(user == null) {
            User user1 = new User();
            user1.setUserName(name);
            user1.setUserNickname(nickname);
            user1.setTelNum(tel);
            user1.setPassword(password);
            user1.setCreateTime(new Timestamp(System.currentTimeMillis()));
            userDao.insert(user1);
            return Result.SUCCESS;
        }else{
            Result result = Result.FAIL;
            result.setMsg("此手机号已经注册过！");
            return result;
        }
    }

    @Override
    public Result login(String name, String password) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_name",name);
        User user = userDao.selectOne(wrapper);
        if(user == null) {
            Result result = Result.FAIL;
            result.setMsg("用户不存在");
            return result;
        } else if(!password.equals(user.getPassword())){
            Result result = Result.FAIL;
            result.setMsg("密码错误");
            return result;
        }else{
            return new Result(userDao.selectOne(wrapper));
        }
    }

    @Override
    public Result delUser(Integer userId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("use_id",userId);
        userDao.delete(wrapper);
        return Result.SUCCESS;
    }

    @Override
    public Result alterUser(Integer userId,String nickname, String password) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("use_id",userId);
        User user = userDao.selectOne(wrapper);
        user.setUserNickname(nickname);
        user.setPassword(password);
        userDao.updateById(user);

        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.eq("use_id",userId);
        return new Result(userDao.selectOne(wrapper));
    }


}
